package xhwl.insurance.http.api;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import rx.Observable;
import xhwl.insurance.dialog.LoadingDialog;
import xhwl.insurance.http.ApiService;
import xhwl.retrofitrx.BaseApi;

/**
 * 上传图片修改
 */

public class UploadPicApi extends BaseApi {
    File[] files;
    Context mContext;
    int count;
    LoadingDialog dialog;
    HashMap<Integer,Boolean> hashMap=new HashMap<>();//保存是否第一次调用
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(dialog!=null&&dialog.isShowing()){
                dialog.setText("请稍候.."+(++msg.what)+"/"+count);
            }

        }
    };
    public void hideDialog(){
        if(dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
        }
    }
    public UploadPicApi(Context context,File... files) {
        this(context,true,files);
    }
    public UploadPicApi(Context context,boolean showDialog,File... files) {
        this.files=files;
        this.count=files.length;
        this.mContext=context;
        setShowDialog(false);
        hashMap.clear();
        for(int i=0;i<files.length;i++){
            hashMap.put(i,true);
        }
        if(showDialog){
            dialog=new LoadingDialog(mContext,"请稍候..");
            dialog.show();
        }
        setShowErrorMsg(false);

    }
    ProgressListener listener=new ProgressListener() {
        @Override
        public void onProgress(long totalSize, long currSize, boolean done, int id) {
            Log.e("tag11"," id="+id+"  "+(currSize) * 100 / totalSize + "%");
            if(done){//此处回调两次
                if(hashMap.get(id)){
                    hashMap.put(id,false);
                    return;
                }
                handler.sendEmptyMessage(id);
            }
        }
    };
    @Override
    protected Observable getObservable() {

        MultipartBody.Builder builder= new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("f_count", files.length+"");
        for(int i=0;i<files.length;i++){
            ProgressRequestBody fileRequestBody = new ProgressRequestBody(i
                    , MediaType.parse("image/*")
                    , files[i]
                    , listener);
            builder.addFormDataPart("pic_"+i, files[i].getName(), fileRequestBody);
        }
        RequestBody requestBody=builder.build();
        return retrofit.create(ApiService.class).uploadpic(requestBody);
    }

    private class ProgressRequestBody extends RequestBody {
        MediaType contentType;
        File file;
        ProgressListener listener;
        int id;

        /**
         * 构造函数
         *
         * @param id          一次可以上传多个文件,id表示本文件在这一批文件当中的编号
         * @param contentType MIME类型
         * @param file        要上传的文件
         * @param listener    传输进度监听器
         */
        public ProgressRequestBody(int id, MediaType contentType, File file, ProgressListener listener) {
            this.id = id;
            this.contentType = contentType;
            this.file = file;
            this.listener = listener;
        }


        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() throws IOException {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            long len;//记录本次读了多少数据
            long currSize = 0;//记录目前一共读了多少数据
            long totalSize = contentLength();//一共有多少数据

            try {
                source = Okio.source(file);
                Buffer buffer = new Buffer();

                while ((len = source.read(buffer, 2048)) != -1) {
                    sink.write(buffer, len);
                    sink.flush();
                    currSize += len;

                    //回调,进度监听
                    listener.onProgress(totalSize, currSize, totalSize == currSize, id);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 传输进度监听器
     */
    public interface ProgressListener {
        void onProgress(long totalSize, long currSize, boolean done, int id);
    }

}
